package com.itlong.cloud.sms;

import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.node.XMLParser;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 *<desc>
 *     短信模块实现类
 *</desc>
 *
 * @author cuiduanwu
 * @create 2017/9/19
 */
@Service
public class SmsMsgService {
    private static final Logger LOG = LoggerFactory.getLogger(SmsMsgService.class);

    // 邮件发送协议
    private final static String PROTOCOL = "smtp";

    // SMTP邮件服务器
    private final static String HOST = "smtphz.qiye.163.com";

    //开启ssl
    private String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    // SMTP邮件服务器默认端口
    private final static String PORT = "994";

    // 是否要求身份认证
    private final static String IS_AUTH = "true";

    // 是否启用调试模式（启用调试模式可打印客户端与服务器交互过程时一问一答的响应消息）
    private final static String IS_ENABLED_DEBUG_MOD = "true";

    // 发件人
    private static String userFrom = "service@itlong.com.cn";

    //第三方发送授权码
    private static String  authorizationCode="yBXttHhvVITLONG2";

    /**
     *<desc>
     *     根据手机号发送短信验证码
     *</desc>
     *
     * @param phoneNo 发送验证码的手机号码
     * @param content 发送的短信内容
     * @return
     * @author Jiaqi.X
     * @creaetDate 2018/05/22
     */
    public boolean  sendSmsCodeByPhone(String phoneNo, String content){
        LOG.info("【APP_登录注册版块_sendSmsCodeByPhone】:发送短信--"+content);
        boolean flag = false;
        String result = null;
        try {
            String send = String.format("%s?action=%s&userid=%s&account=%s&password=%s&mobile=%s&content=%s",
                    PlatformConstants.SMS_MESSAGE_ACTION_URL, "send", PlatformConstants.SMS_MESSAGE_ID, PlatformConstants.SMS_MESSAGE_ACCOUNT,
                    PlatformConstants.SMS_MESSAGE_PASSWORD, phoneNo, URLEncoder.encode("【云半径】" + content, "UTF-8"));
            result = HttpProtocolUtil.doGet(send, new HashMap<>());
            Map<Object,Object> resultMap  = XMLParser.xmlString2Map(result);
            LOG.info("短信发送结果--"+ JsonUtil.toJSON(resultMap));
            if (resultMap.get("returnstatus").toString().equals("Success")) {
                flag = true;
            }
        } catch (Exception e) {
            LOG.error("【APP_登录注册版块_sendSmsCodeByPhone】:发送短信失败--" + result + "--" + e.getMessage());
        }
        return  flag;
    }


//    public static void main(String[] args) {
//        SmsMsgService smsMsgService = new SmsMsgService();
//        smsMsgService.sendSmsCodeByEmail("kumamou@163.com","验证码:789");
//    }


    /**
     * <desc>
     *      发送简单的文本邮件。
     * <desc/>
     *
     * @param  emailAddress 邮件地址
     * @param  content 提示信息
     * @return
     * @author shengen.T
     * @createDate 2017-12-29
     */
    public boolean sendSmsCodeByEmail(String emailAddress,String content) {
        content = PlatformConstants.SMS_MESSAGE_INTERNATIONAL_SIGN+content;
        LOG.info("【APP_登录注册版块_sendSmsCodeByEmail】:发送注册验证码--"+content);
        try {
            // 初始化连接邮件服务器的会话信息
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", PROTOCOL);
            props.setProperty("mail.smtp.host", HOST);
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.port", PORT);
            props.setProperty("mail.smtp.auth", IS_AUTH);
            props.setProperty("mail.debug",IS_ENABLED_DEBUG_MOD);
            // 创建Session实例对象
            Session session1 = Session.getDefaultInstance(props);

            // 创建MimeMessage实例对象
            MimeMessage message = new MimeMessage(session1);
            // 设置发件人
            String nick = "ITLONG";
            message.setFrom(new InternetAddress(nick+"<"+userFrom+">"));
            // 设置邮件主题
            message.setSubject("Jia-R Verification Code");
            // 设置收件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));
            // 设置发送时间
            message.setSentDate(new Date());
            // 设置纯文本内容为邮件正文
            message.setText(content);
            // 保存并生成最终的邮件内容
            message.saveChanges();

            // 获得Transport实例对象
            Transport transport = session1.getTransport();
            // 打开连接
            transport.connect(userFrom, authorizationCode);
            // 将message对象传递给transport对象，将邮件发送出去
            transport.sendMessage(message, message.getAllRecipients());
            // 关闭连接
            transport.close();

            return true;
        } catch (Exception e) {
            LOG.error("【APP_登录注册版块_sendSmsCodeByEmail】:发送邮箱验证码失败--"+ e.getMessage());
            return false;
        }
    }



}
